package com.dq.service.sys.user.impl;

import com.dq.context.Constant;
import com.dq.exception.customException.AdminException;
import com.dq.controller.in.user.SysSectionUserQuery;
import com.dq.controller.in.base.BaseAdminQuery;
import com.dq.vo.ListDataVo;
import com.dq.vo.Vo;
import com.dq.vo.baseVo.VO;
import com.dq.domain.base.impl.BaseDaoImpl;
import com.dq.domain.sys.role.SysUserRole;
import com.dq.domain.sys.section.SysSection;
import com.dq.domain.sys.user.user.base.BackUser;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.repository.BaseRepositories;
import com.dq.service.sys.user.BackUserService;
import com.google.common.base.Joiner;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author  cf
 */
@Service
public class BackUserServiceImpl extends BaseRepositories implements BackUserService {
    /**
     * 获取组织结构下的所有用户, bossuser/orguser
     * 可以设定是否只显示 自己创建的用户
     */
    @Override
    public Vo backUserList(SysSectionUserQuery sectionUserQuery) throws AdminException {
        SysUser loginUser = sysUserService.getUserInSection();
        /// 只有超级管理员，才能查看所有管理员列表
//        SysUser user = sysUserService.getUser();
//        if (String.valueOf(Constant.ADMIN_ID).equals(user.getId().toString())) {
//            sectionUserQuery.setCreateUser(user);
//        }

        sectionUserQuery.format();
        Map<String, Object> query = sectionUserQuery.parseMap();

        if(sectionUserQuery.getEntryTimeEnd() != null) {
            query.put("entryTime" + BaseDaoImpl.lteSqlStr, sectionUserQuery.getEntryTimeEnd());
            query.remove("entryTimeBegin");
        }
        if(sectionUserQuery.getEntryTimeBegin() != null) {
            query.put("entryTime" + BaseDaoImpl.gteSqlStr, sectionUserQuery.getEntryTimeBegin());
            query.remove("entryTimeEnd");
        }
        if(sectionUserQuery.getEndTime() != null) {
            query.put("createTime" + BaseDaoImpl.lteSqlStr, sectionUserQuery.getEndTime());
            query.remove("endTime");
        }
        if(sectionUserQuery.getBeginTime() != null) {
            query.put("createTime" + BaseDaoImpl.gteSqlStr, sectionUserQuery.getBeginTime());
            query.remove("beginTime");
        }
        if (StringUtils.isNotBlank(sectionUserQuery.getUsername())) {
            query.put("username" + BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(sectionUserQuery.getUsername()));
            query.remove("username");
        }
        if (StringUtils.isNotBlank(sectionUserQuery.getUserRealcName())) {
            query.put("userRealcName" + BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(sectionUserQuery.getUserRealcName()));
            query.remove("userRealcName");
        }
//        if(sectionUserQuery.roleId != null) {
//
//        }

        List<Long> sectionIdList = new ArrayList<>();
        if(sectionUserQuery.getSectionId() != null) {
            boolean isPar = false;
            SysSection section = dao.get(SysSection.class, sectionUserQuery.getSectionId());
            if(StringUtils.isNotBlank(section.getAncestors())) {
                String[] split = section.getAncestors().split(",");
                for (String s : split) {
                    if(s.equals(loginUser.getSection().getId().toString())) {
                        isPar = true;
                        break;
                    }
                }
            }else {
                if(loginUser.getId().toString().equals(String.valueOf(Constant.ADMIN_ID))) {
                    isPar = true;
                }
            }

            Long sectionIdGetList;
            if(isPar) {
                sectionIdGetList = sectionUserQuery.getSectionId();
                sectionIdList.add(sectionUserQuery.getSectionId());
            }else {
                sectionIdGetList = loginUser.getSection().getId();
                sectionIdList.add(loginUser.getSection().getId());
            }
            //        List<SysSection> sectionList = dao.findBySql(SysSection.class, String.format("SELECT t.* FROM sys_section t WHERE FIND_IN_SET (%s, t.ancestors)", sectionIdGetList));
//            for (SysSection sysSection : sectionList) {
//                sectionIdList.add(sysSection.getId());
//            }
        }else {
            sectionIdList.add(loginUser.getSection().getId());
            List<SysSection> sectionList = dao.findBySql(SysSection.class, String.format("SELECT t.* FROM sys_section t WHERE FIND_IN_SET (%s, t.ancestors)", loginUser.getSection().getId()));
            for (SysSection sysSection : sectionList) {
                sectionIdList.add(sysSection.getId());
            }
        }

        query.put("section_id" + BaseDaoImpl.inSqlStr, sectionIdList);
        query.remove("sectionId");

        List<BackUser> list = dao.find(dao.query2Hql(BackUser.class, query), query);
        Long count = dao.count(dao.count2Hql(BackUser.class, query), query);
        for(BackUser back : list){
            SysUser sysUser = dao.get(SysUser.class,back.getId());
            List<SysUserRole> sysUserRoles = sysUserRoleRepository.findBySysUserAndDeletedFalseAndSysRoleDeletedFalse(sysUser);
            List<Long> roleIds = new ArrayList<>();
            List<String> roleNames = new ArrayList<>();
            sysUserRoles.forEach(sysUserRole -> {
                roleIds.add(sysUserRole.getSysRole().getId());
                roleNames.add(sysUserRole.getSysRole().getRoleName());
            });
            back.setRoleIds(Joiner.on(",").join(roleIds));
            back.setRoleNames(Joiner.on(",").join(roleNames));
        };

        return new ListDataVo((List<BackUser.Vo>) VO.toVOCollection(list), count);
    }

}
